<?php

class ArquivosController extends AppController {
	var $helpers = array('Html','Form','Accessibility','Pagination', 'Associations','Input');
	var $uses = array('Arquivo','Configuration');
	var $components = array('Upload');
	
	function upload() {	
		// Retrieving organization's data 
		$organization = $this->othAuth->getData('organization');
				
		$title = 'Adicionar arquivo';
		$this->set('title', $title);
		$this->set('pageTitle', $title);
	
		if (!empty($this->data)) { 
			if (is_uploaded_file($this->data['Arquivo']['File']['tmp_name'])) {
				/* checking quota */
				$sum = $this->Arquivo->find('all', array('fields'=>array('SUM(size) AS total_sum'),
	                                         'conditions'=>array('Arquivo.organization_id'=>$organization['id']),
	                                         'recursive'=>-1));
				$used = ($sum[0][0]['total_sum']);
				
				$configuration_quota = $this->Configuration->find('first', array('conditions'=>array('name'=>'download_quota')));
				$quota = ($configuration_quota['Configuration']['value']);
				
				if (($used + $this->data['Arquivo']['File']['size']) > $quota) {
					$_SESSION['mensagem']['error'][] = 'Quota estourada.';
				}
				

				$file = $this->data['Arquivo']['File'];
				
				// Retrieving data from uploaded file
				$size = $this->data['Arquivo']['File']['size'];
			    	
				// Getting file extension
				$extensions = explode(".",$this->data['Arquivo']['File']['name']);
				$extension = $extensions[sizeof($extensions)-1];

				
				// Generating file's path and name
				$path = '/cms/'.$organization['id'];
				$filename = $this->data['Arquivo']['name'].'.'.$extension;

				// set the upload destination folder
				$destination = realpath('../../app/webroot/') . $path.'/';

				// 	Creating folder for organization
				if(!is_dir($destination)) {
					mkdir($destination, 0777);
				}
				
				if (!isset($_SESSION['mensagem']['error'])) {
					// upload the image using the upload component
					$result = $this->Upload->upload($file, $destination, $this->data['Arquivo']['File']['name'], NULL, array('*'));
									
					// Creating information about created file				
				   	$this->data['Arquivo']['type'] = $this->data['Arquivo']['File']['type'];
				   	$this->data['Arquivo']['size'] = $this->data['Arquivo']['File']['size'];
				   	$this->data['Arquivo']['path'] = $path."/".$this->data['Arquivo']['File']['name'];
				   	//$this->data['Arquivo']['data'] 				= $fileData;
					$this->data['Arquivo']['organization_id'] = $organization['id'];
		
					// Saving information on database
				   $this->Arquivo->save($this->data);
		
					// Redirecting to File List     
					$_SESSION['mensagem']['success'][] = 'Arquivo adicionado com sucesso!';       
					$this->redirect('/arquivos/index');
				} 
			} else {
				// Display "Invalid File" error message
			}
		}
	}
	
	function edit($id=NULL) {
		// Retrieving organization's data 
		$organization = $this->othAuth->getData('organization');
		
		if (!$id) $this->redirect('/arquivos');
		$title = 'Editar arquivo';
		$this->set('title', $title);
		$this->set('pageTitle', $title);
		
		$this->Arquivo->id = $id;
		if (empty($this->data)) {
			$this->data = $this->Arquivo->read();
		} else {
			if (!empty($this->data)) { 
				if (is_uploaded_file($this->data['Arquivo']['File']['tmp_name'])) {
			
					/* checking quota */
					$sum = $this->Arquivo->find('all', array('fields'=>array('SUM(size) AS total_sum'),
		                                         			  'conditions'=>array('id <>'=> $id, 
		                                         			  'Arquivo.organization_id'=>$organization['id']),
		                                         'recursive'=>-1));
					$used = ($sum[0][0]['total_sum']);
					$configuration_quota = $this->Configuration->find('first', array('conditions'=>array('name'=>'download_quota')));
					$quota = ($configuration_quota['Configuration']['value']);
					
					if (($used + $this->data['Arquivo']['File']['size']) > $quota) {
						$_SESSION['mensagem']['error'][] = 'Quota estourada.';
					}
					
					$file = $this->data['Arquivo']['File'];
					
					// Retrieving data from uploaded file
					$size = $this->data['Arquivo']['File']['size'];
				    	
					// Getting file extension
					$extensions = explode(".",$this->data['Arquivo']['File']['name']);
					$extension = $extensions[sizeof($extensions)-1];
	
					
					// Generating file's path and name
					$path = '/cms/'.$organization['id'];
					$filename = $this->data['Arquivo']['name'].'.'.$extension;
	
					// set the upload destination folder
					$destination = realpath('../../app/webroot/') . $path.'/';
	
					// 	Creating folder for organization
					if(!is_dir($destination)) {
						mkdir($destination, 0777);
					}
					if (!isset($_SESSION['mensagem']['error'])) {
						// upload the image using the upload component
						$result = $this->Upload->upload($file, $destination, $this->data['Arquivo']['File']['name'], NULL, array('*'));
										
						// Creating information about created file				
					   	$this->data['Arquivo']['type'] = $this->data['Arquivo']['File']['type'];
					   	$this->data['Arquivo']['size'] = $this->data['Arquivo']['File']['size'];
					   	$this->data['Arquivo']['path'] = $path."/".$this->data['Arquivo']['File']['name'];
					   	//$this->data['Arquivo']['data'] 				= $fileData;
						$this->data['Arquivo']['organization_id'] = $organization['id'];
			
						// Saving information on database
					   $this->Arquivo->save($this->data);
			
						// Redirecting to File List     
						$_SESSION['mensagem']['success'][] = 'Arquivo adicionado com sucesso!';       
						$this->redirect('/arquivos/index');
					}
				} else {
					// Display "Invalid File" error message
				}
			}
		}
		$arquivo = $this->Arquivo->find(array('`Arquivo`.id' => $id));
		$this->set('arquivo', $arquivo);
	}
	
	function delete($id=NULL) {
		if (!$id) $this->redirect('/arquivos');
		
		$arquivo = $this->Arquivo->find(array('`Arquivo`.id' => $id));
		$path = $arquivo['Arquivo']['path'];
		$destination = realpath('../../app/webroot/') . $path;
		
		if ($this->Arquivo->del($id)) {
			if (unlink($destination)) {	
				$_SESSION['mensagem']['success'][] = 'Arquivo excluido com sucesso!';

			} else {
				$_SESSION['mensagem']['error'][] = 'Erro ao tentar excluir o arquivo.';
			}
		} else {
			$_SESSION['mensagem']['error'][] = 'Erro ao tentar excluir o arquivo.';
		}
		$this->redirect('/arquivos');
	}
	
	function index()
	{
		// Retrieving organization's data 
	 	$organization = $this->othAuth->getData('organization');
	
		$title = 'Arquivos';
		$this->set('title', $title);
		$this->set('pageTitle', $title);
	
		$arquivos = $this->Arquivo->find('all', array('organization_id' => $organization['id']));
	
		$sum = $this->Arquivo->find('all', array('fields'=>array('SUM(size) AS total_sum'),
	                                         'conditions'=>array('Arquivo.organization_id'=>$organization['id']),
	                                         'recursive'=>-1));
		$used = ($sum[0][0]['total_sum'])/(1024*1024);

		$configuration_quota = $this->Configuration->find('first', array('conditions'=>array('name'=>'download_quota')));
		$quota = ($configuration_quota['Configuration']['value'])/(1024*1024);
		 
		$this->set('arquivos', $arquivos);
		$this->set('used', $used);
		$this->set('quota', $quota);
	}
	
	function view($id)
	{
		$arquivo = $this->Arquivo->find(array('id' => $id));
	
		$this->set('arquivo', $arquivo);
	
		$title = 'Visualizando arquivo '.$arquivo['Arquivo']['name'] ;
		$this->set('title', $title);
		$this->set('pageTitle', $title);
	}
	
	function gallery()
	{
		//TODO
	}

} 


